<!-- 我的参与记录 -->
<template>
  <view :class="isIpx ? 'fix-iphonex-info' : ''">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
<!--    <view class="tab-box">
      <view class="tab-inner">
        <view class="top-tab" @click="changeTab(0)">不凡甄选
          <image v-if="actTab == 0" class="act_img" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/Vector_icon.png"></image>
        </view>
        <view class="top-tab" @click="changeTab(1)">活动预约
          <image v-if="actTab == 1" class="act_img" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/Vector_icon.png"></image>
        </view>
      </view>
    </view> -->
    <!-- 参与记录 -->
    <block v-if="actTab == 0">
      <view class="listBox" v-if="!is_empty">
        <block v-for="(item, index) in listData" :key="index">
          <view class="item" @click="jumpPage(item)" >
            <view class="img">
              <image :src="item.frontUrl" mode="widthFix"></image>
            </view>
            <view class="item_right">
              <view class="goodsTitle">
                <view class="goods_name">{{item.itemName}}</view>
                <view class="text-red goodsTitle-text" :style="{color: item.textColor}">{{item.status}}</view>
              </view>
              <view class="luckyCode" :style="{opacity: item.luckyCode ? 1 : 0}">中签码：{{item.luckyCode}}</view>
              <view class="time">{{item.operateType}}：{{item.operateTimes}}</view>
            </view>
          </view>
        </block>
      </view>
      <view class="tips_text" :class="bottomtextPos ? 'pos_margin':'pos_absolute'">--仅显示当月的活动记录--</view>
      <!--暂无数据显示-->
      <block v-if="is_empty">
        <view class="empty_list_box">
          <image class="empty_img" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/empty_cart_logo4x.png" />
          <view class="empty_text">暂无登记记录</view>
          <view class="empty_btn"  @click="goHomePage">探索更多</view>
        </view>
      </block>
      <view class="ios_safe_zone" v-if="isIos">
        <view class="ios_safe_zone_line"></view>
      </view>
    </block>
    <!-- 活动预约 -->
    <block v-else>
      <view class="empty_list_box">
        <image class="empty_img" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/empty_cart_logo4x.png" />
        <view class="empty_text">您可查询近期活动预约记录</view>
        <view class="empty_btn" @click="changeTab(2)">即刻查看</view>
      </view>
    </block>
    <loading :showLoaded.sync="showLoaded"></loading>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
  import api from '@/api/api';
  import util from '@/utils/util';
  import NavBar from '../../components/common/navbar';
  import Loading from '../../components/common/loading';
  import Placeholder from '@/components/common/placeholder';
  import {
    SYSTEM_INFO,
    USER_INFO,
    USER_SPECICAL_INFO,
    CUSTOMER_INFO,
    MERCHANT_INFO,
    LOWER_WX_VERSION
  } from '@/utils/constant';
  export default {
    components: {
      navBar: NavBar,
      loading: Loading,
      placeholder: Placeholder,
    },
    data() {
      return {
        actTab: 0,
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '',
          hideSearch: true,
          hideHome: false,
        },
        showLoaded: true,
        isShowCustomNavBar: true,
        listData: {},
        is_empty: false,
        isIpx: false,
        activityStopTime: "",
        nowPages: '',
        bottomtextPos: false,  // true:margin-top/false:定位
        isIos: false
      }
    },
    onLoad: async function(option) {
      let that = this;
      this.isIos = 	wx.getSystemInfoSync().system.includes('iOS') && wx.getSystemInfoSync()?.safeArea?.top>20;

      this.isIpx = getApp().globalData.isIpx;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      that.recordList(customerInfo.jwt);
      let pages = getCurrentPages();
      var currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
    },
    onShow() {
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '我的参与记录',
      })
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      goHomePage(){
        uni.reLaunch({
          url: '/pages/home/home',
          success: function(e) {
            var page = getCurrentPages().pop();
            if (page == undefined || page == null) return;
            page.onLoad();
          }
        });
      },
      changeTab(index) {
        this.actTab = index === 0 ? 0 : 1
        let clTrackPrams = {}
        if(index === 2) {
          getApp().commonClTrack('c_ebmp_my_participation_record_view_now', clTrackPrams)
        } else {
          clTrackPrams = {
            'c_area': index == 0 ? '不凡甄选' : '活动预约'
          }
          getApp().commonClTrack('c_ebmp_my_participation_record_click_tab', clTrackPrams)
        }
        if(index === 1 || index === 2) {
          uni.openEmbeddedMiniProgram({
          	appId: 'wxd77b68985ec0c0ef',
          	path: 'pages/AlcoholCondition/myActiveList?flag21=21',
            // envVersion: 'trial',
          	extraData: {
          		'data1': 'test'
          	},
          	success(res) {

              // 打开成功
          	},
            complete(res) {

            }
          })
        }
      },
      async recordList(jwt) {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const recordListResult = await api.recordList({
          header: {
            jwt: customerInfo.jwt || jwt
          },
          query: {
            page_no: 1,
            page_size: 100,
          }
        });
        if (recordListResult.code == 1000 && recordListResult.data) {
          let _listData = recordListResult.data.content;
          that.is_empty = _listData.length ? false : true;
          let systemInfo = uni.getStorageSync(SYSTEM_INFO);
          let isIos = systemInfo.system.indexOf('iOS')
          let nowTime = new Date().getTime() / 1000;
          for(let i=0;i<_listData.length;i++){
            const el = _listData[i];

            let date = el.operateTime || ''
            let arr = date.split('-')
            let splitDate = arr[0] + '-' + arr[1] + '-' + arr[2]
            // let newDate = splitDate.replace(" ", "日 ");
            el.operateTimes = splitDate;
            if (isIos == 0) {
              el.activityStopTime = new Date(el.activityStopTime.replace(/-/g, '/')).getTime() / 1000;
            } else {
              el.activityStopTime = new Date(el.activityStopTime).getTime() / 1000;
            }
            if(el.activityStopTime > nowTime){
              el.classStyle ='black'
            } else {
              el.classStyle ='grey'
            }
            const _arr1 = ['已订阅提醒','已登记', '未中签', '已取消', '活动结束']
            if(_arr1.includes(el.status)){
              el.luckyCode = "";
            }
            if (el.status == "已订阅提醒") {
              el.textColor = "#CB171A";
              el.operateType = "订阅时间";
            } else if (el.status == "已登记") {
              el.textColor = "#CB171A";
              el.operateType = "登记时间";
            } else if (el.status == "登记结束") {
              el.textColor = "#757575";
              el.operateType = "登记时间";
            } else if (el.status == "恭喜中签") {
              el.textColor = "#CB171A";
              el.operateType = "公布时间";
            } else if (el.status == "待支付") {
              el.textColor = "#CB171A";
              el.operateType = "提交订单时间";
            } else if (el.status == "已支付") {
              el.textColor = "#CB171A";
              el.operateType = "支付时间";
            } else if (el.status == "未中签") {
              el.textColor = "#757575";
              el.operateType = "公布时间";
            } else if (el.status == "交易完成") {
              el.textColor = "#CB171A";
              el.operateType = "交易完成时间";
            } else if (el.status == "活动结束") {
              el.textColor = "#757575";
              el.operateType = "结束时间";
            } else if (el.status == "已取消") {
              el.textColor = "#757575";
              el.operateType = "取消时间";
            }else if (el.status == "已退款") {
              el.textColor = "#757575";
              el.operateType = "退款时间";
            }else if (el.status == "已关闭") {
              el.textColor = "#757575";
              el.operateType = "关闭时间";
            }else {
              el.textColor = "#757575";
              el.luckyCode = "";
            }
            //  查询商品高清大图
            const _goodsRes = await that.getDetailsById(merchantInfo, el.itemId)
            if(_goodsRes.img) el.frontUrl = _goodsRes.img;
            if(_goodsRes.subtitle) el.itemName = _goodsRes.subtitle;
          }
          that.listData = _listData;
          that.showLoaded = false;

          that.handleSetTips();

        } else {
          that.handleShowTextToast(recordListResult.msg);
        }
      },
      async jumpPage(item) {
        try{
          let that = this;
          let itemId = item.itemid;
          let valueId = item.valueid;
          let activityStopTime = item.activityStopTime
          let nowTime = new Date().getTime() / 1000;
          const json = await api.getServerTime({
            method: "POST",
            query: {},
          });
          if (json.code === 1000 && json.data) {
            let time = JSON.parse(json.data);
            nowTime = time.server_date / 1000;
          }
          if (activityStopTime > nowTime) {
            uni.navigateTo({
              url: `/pages/item/item?id=${item.itemId}&valueId=${item.valueId}`
            });
          } else {
            return false;
          }
        }catch(e){

        }
      },
      /**
       * 获取商品详情
       * @param {Object} merchantInfo
       * @param {Object} itemId
       */
      async getDetailsById(merchantInfo, itemId){
        return new Promise(async (resolve, reject)=>{
          const _res = await api.goodsDetail({
              query: {
                merchant_id: merchantInfo.cloudMerchantId,
                store_id: merchantInfo.cloudMerchantStoreId
              }
            },
            itemId
          );
          let _img = "";
          let _subtitle = "";
          if(_res && _res.code == 1000 && _res.data){
            if(_res.data.resources && _res.data.resources.length){
              const _obj = _res.data.resources.find((item)=>item.kind == "hdlp");
              if(_obj && _obj.kind == "hdlp" && _obj.type == "image" && _obj.url) _img = _obj.url;
            }
            if(_res.data.frontProperties && _res.data.frontProperties[0]){
              if(_res.data.frontProperties[0].subtitle) _subtitle = _res.data.frontProperties[0].subtitle;
            }
          }
          resolve({img:_img,subtitle:_subtitle})
        })
      },
      //  动态获取内容区域高度
      handleSetTips(){
        const that = this;
        const _device = uni.getWindowInfo();
        const _statusBarHeight = _device.statusBarHeight;
        let rect = uni.getMenuButtonBoundingClientRect ? uni.getMenuButtonBoundingClientRect() : null; //胶囊按钮位置信息
        let navBarHeight = (function() {
          //导航栏高度
          let gap = rect.top - _statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
          return 2 * gap + rect.height;
        })();
        const _h = _device.safeArea.height - navBarHeight - _statusBarHeight;
        setTimeout(()=>{
          uni.createSelectorQuery().select('.listBox').boundingClientRect().exec((res)=>{
            if(res && res[0]){
              that.bottomtextPos = res[0].height >= _h ? true : false
            }
          })
        }, 500)
      }
    }
  }
</script>

<style lang="less">
  page {
    font-family: FrankNew-Regular,NotoSansSC-Regular;
  }
  .listBox {
    margin-top: 20rpx;
    padding: 0 48rpx;

    .item {
      margin-bottom: 32rpx;
      background-color: #fafafa;
      display: flex;

      .img {
        width:120rpx;
        height:160rpx;
        margin: 30rpx 46rpx 30rpx 12rpx;
        flex-shrink: 0;
        image {
          width:100%;
          height:100%;
        }
      }

      .black{
        color: #000;
      }
      .goodsTitle {
        display: flex;
        justify-content: space-between;
        color: #000;
        font-size: 28rpx;
        font-weight: 500;
        line-height: 40rpx;
        height: 40rpx;
        width:444rpx;
        margin-top: 32rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-family: FrankNew-Medium,NotoSansSC-Medium;
        &.black{
          color: #000;
        }
      }

      .time {
        color: #757575;
        margin-top: 36rpx;
        font-size: 24rpx;
        font-weight: 500;
        line-height: 40rpx;
        // font-family: FrankNew-Medium,NotoSansSC-Medium;
        &.black{
          color: #000;
        }
      }
    }
  }
  .item_right{
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    flex-direction: column;
  }
  .tips_text{
    width:100%;
    color: #c6c6c6;
    font-size: 24rpx;
    font-weight: 500;
    line-height: 32rpx;
    text-align: center;
  }
  .pos_absolute {
    position: fixed;
    left: 0;
    bottom: 62rpx;
  }

  .pos_margin {
    padding: 80rpx 0;
  }
  .fix-iphonex-info {
    padding-bottom: 30rpx;
  }
  .empty_list_box{
    margin-top: 256rpx;
  }
  .empty_img{
    width: 108.38rpx;
    height: 80rpx;
    display: block;
    margin: 0 auto;
  }
  .empty_text{
    width: 100%;
    line-height: 48rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: normal;
    font-family: NotoSansSC-Regular;
    margin-top: 80rpx;
  }
  .empty_btn{
    width: 176rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 48rpx 16rpx 48rpx 48rpx;
    background-color: #CB171A;
    color: #fff;
    font-size: 28rpx;
    font-weight: 500;
    text-align: center;
    margin: 80rpx auto 0 auto;
    font-family: NotoSansSC-Medium;
  }
  .tab-box{
    width:100%;
    height: 120rpx;
  }
  .tab-inner {
    height: 114rpx;
    border-bottom: 1px solid #f2f2f2;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;;
    align-items: center;
    padding: 0 48rpx;
  }
  .top-tab {
    width: 327rpx;
    height: 112rpx;
    line-height: 112rpx;
    text-align: center;
    position: relative;
  }
  .line-border {
    width: 2rpx;
    height: 30rpx;
    opacity: 1;
    background: #E7E7E7;
  }
  .act_img{
    width: 28rpx;
    height: 14rpx;
    position: absolute;
    left: 50%;
    margin-left: -14rpx;
    bottom: -6rpx;
  }
  .goodsTitle-text{
    width: 130rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    font-weight: 500;
    font-family: FrankNew-Medium,NotoSansSC-Medium;
    text-align: right;
  }
  .goods_name{
    width: 280rpx;
    line-height: 40rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .text-red{
    color: #CB171A;
  }
  .text-antiquewhite{
    color: #757575;
  }
  .luckyCode{
    font-size: 20rpx;
    line-height: 40rpx;
    color: #757575;
  }
</style>
